package com.example.dao;

import com.example.bean.Medicine;
import com.example.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 药材数据访问对象
 */
public class MedicineDAO {

    /**
     * 查询所有药材
     */
    public List<Medicine> findAll() {
        List<Medicine> medicines = new ArrayList<>();
        String sql = "SELECT * FROM medicine ORDER BY id DESC";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                medicines.add(extractMedicine(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return medicines;
    }

    /**
     * 根据ID查询药材
     */
    public Medicine findById(int id) {
        String sql = "SELECT * FROM medicine WHERE id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                return extractMedicine(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return null;
    }

    /**
     * 搜索药材（按药材名、编号或功能介绍）
     */
    public List<Medicine> search(String keyword) {
        List<Medicine> medicines = new ArrayList<>();
        String sql = "SELECT * FROM medicine WHERE medicine_name LIKE ? OR medicine_no LIKE ? OR main_function LIKE ? ORDER BY id DESC";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            String searchPattern = "%" + keyword + "%";
            pstmt.setString(1, searchPattern);
            pstmt.setString(2, searchPattern);
            pstmt.setString(3, searchPattern);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                medicines.add(extractMedicine(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return medicines;
    }

    /**
     * 添加药材
     */
    public boolean add(Medicine medicine) {
        String sql = "INSERT INTO medicine (medicine_no, medicine_name, alias, source, environment, " +
                    "nature_flavor, main_function, usage_dosage) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, medicine.getMedicineNo());
            pstmt.setString(2, medicine.getMedicineName());
            pstmt.setString(3, medicine.getAlias());
            pstmt.setString(4, medicine.getSource());
            pstmt.setString(5, medicine.getEnvironment());
            pstmt.setString(6, medicine.getNatureFlavor());
            pstmt.setString(7, medicine.getMainFunction());
            pstmt.setString(8, medicine.getUsageDosage());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
    }

    /**
     * 更新药材
     */
    public boolean update(Medicine medicine) {
        String sql = "UPDATE medicine SET medicine_no = ?, medicine_name = ?, alias = ?, source = ?, " +
                    "environment = ?, nature_flavor = ?, main_function = ?, usage_dosage = ? WHERE id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, medicine.getMedicineNo());
            pstmt.setString(2, medicine.getMedicineName());
            pstmt.setString(3, medicine.getAlias());
            pstmt.setString(4, medicine.getSource());
            pstmt.setString(5, medicine.getEnvironment());
            pstmt.setString(6, medicine.getNatureFlavor());
            pstmt.setString(7, medicine.getMainFunction());
            pstmt.setString(8, medicine.getUsageDosage());
            pstmt.setInt(9, medicine.getId());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
    }

    /**
     * 删除药材
     */
    public boolean delete(int id) {
        String sql = "DELETE FROM medicine WHERE id = ?";
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
    }

    /**
     * 从ResultSet中提取Medicine对象
     */
    private Medicine extractMedicine(ResultSet rs) throws SQLException {
        Medicine medicine = new Medicine();
        medicine.setId(rs.getInt("id"));
        medicine.setMedicineNo(rs.getString("medicine_no"));
        medicine.setMedicineName(rs.getString("medicine_name"));
        medicine.setAlias(rs.getString("alias"));
        medicine.setSource(rs.getString("source"));
        medicine.setEnvironment(rs.getString("environment"));
        medicine.setNatureFlavor(rs.getString("nature_flavor"));
        medicine.setMainFunction(rs.getString("main_function"));
        medicine.setUsageDosage(rs.getString("usage_dosage"));
        medicine.setCreateTime(rs.getTimestamp("create_time"));
        medicine.setUpdateTime(rs.getTimestamp("update_time"));
        return medicine;
    }
}

